import React, { FC, useEffect, useState, useRef,useMemo } from "react";
import style from "./commonList.module.scss";
import QuestionCardAntUi from "../../components/QuestionCardAntUi";
import { useSearchParams } from "react-router-dom";
import { Typography, Spin, Result, Empty } from "antd";
import SearchList from "../../components/SearchList";
import { useTitle, useRequest, useDebounceFn } from "ahooks";
import { getQuestionListService } from "../../services/question";
import { LIST_PAGE_SIZE, LIST_SEARCH_KEY } from "../../constant";

const { Title } = Typography;

const List: FC = () => {
  useTitle("鸣远问卷  - 问卷列表");
  // const loading = false;
  const [start, setStart] = useState(false); // 开始请求数据时，标记为开始，是让加载显示出来
  const [list, setList] = useState([]); // 列表数据累加
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  // 判断是否还有更多的数据
  const haveMoredata = list.length < total;
  const [searchaParams] = useSearchParams();
  let keyword = searchaParams.get(LIST_SEARCH_KEY) || ""
  // 在滑动时根据底部加载更多div是否露出来判断是否下滑到底部，从而进行列表数据请求
  const container = useRef<HTMLDivElement>(null);
  // 懒加载： 在搜索后，需要重制列表的记录信息
  useEffect(() => {
    setList([])
    setPage(1)
    setTotal(0)
  } , [keyword])

  // 加载数据 --  请求接口
  const { loading, run: lod } = useRequest(
    async () => {
      const data = await getQuestionListService({
        pageIndex: page,
        pageSize: LIST_PAGE_SIZE,
        keyword,
      });
      return data;
    },
    {
      manual: true,
      onSuccess(result) {
        const { total = 0, list: l } = result;
        setList(list.concat(l));
        setTotal(total);
        setPage(page + 1);
      },
    }
  );

  // 触发加载的函数 --- 防抖处理：ahooks
  const { run: tryLoadMore } = useDebounceFn(
    () => {
      // 根据元素距离试图顶部的距离来判断是否需要加载
      const elem = container.current;
      if (!elem) return;
      const domRect = elem.getBoundingClientRect();
      const { bottom } = domRect;
      // ?? 这个判断不对,需要优化： 只要划动就会请求数据
      // console.log(bottom, "50", document.body.clientHeight , window.innerHeight);
      // return
      if (bottom < window.innerHeight) {
        lod();
        setStart(true);
        console.log("加载更多");
      }
    },
    {
      wait: 500,
    }
  );

  // 首次渲染，加再一次，请求第一列数据; 搜索框搜索后，url中有keyword请求参数
  useEffect(() => {
    tryLoadMore();
  }, [searchaParams]);

  useEffect(() => {
    if (haveMoredata) {
      window.addEventListener("scroll", tryLoadMore); // 要考虑防抖
    }
    return () => {
      // 自己绑定的 事件在组件卸载时，一定要解绑
      window.removeEventListener("scroll", tryLoadMore);
    };
  }, [searchaParams, haveMoredata]);

  const lodMoreElement = useMemo(() => {
    if (!start || loading) return <Spin />;
    if (total === 0) return <Empty description="暂无数据" />;
    if (!haveMoredata) return <span>没有更多数据了</span>;
    return <span>开始加载下一页</span>;
  },[start , haveMoredata , loading]);

  return (
    <>
      <div className={style.header}>
        <div className={style.left}>
          <Title level={3}>我的问卷</Title>
        </div>
        <div className={style.right}>
          <SearchList />
        </div>
      </div>
      <div className={style.content}>
        {/* <div style={{ height: "2000px", bac groundColor: "pink" }}></div> */}
        {/* 问卷列表 */}
        {list.length > 0 &&
          list.map((itm: any) => {
            const { _id } = itm;
            return <QuestionCardAntUi key={_id} {...itm} />;
          })}
      </div>
      <div className={style.footer}>
        {/*  list 页不使用分页请求了，使用load more */}
        <div className="aaa" ref={container}>
          {lodMoreElement}
        </div>
      </div>
    </>
  );
};

export default List;
